<?php
/**
 * wondershare站的春假活动页面接口文件
 * @auth huangcb
 * */

define('INTERFACE_CODE', md5('ws-cj-20120229'));
//note 接口合法性验证
if( $_GET['code'] != INTERFACE_CODE ) exit('error code!');

date_default_timezone_set('EST');


define('DB_TABLE_PRE','cj_');//表前缀
define('IMG_SAVE_PATH','/var/www/website/cms.wondershare.com/httpdocs/image2/cj_img/');
define('IMG_UPLOAD_PATH',IMG_SAVE_PATH.'upload/');
define('IMG_BG_PATH',IMG_SAVE_PATH.'bg/');

require_once '../../conf/conf.php';
require_once '../ws_qrj/lib/Mysql.class.php';
require_once '../ws_qrj/lib/Image.class.php';

$db = new Mysql();


//note ws服务器传递图片过来
function uploadimg( $db ){
	require_once '../ws_qrj/lib/Upload.class.php';
	$up = new Upload();
	$im = new Image();
	
	$type = 0;
	_createFolder( IMG_UPLOAD_PATH );
	_createFolder( IMG_BG_PATH );
	
	$img = $up->doUpload( IMG_UPLOAD_PATH, 'imgfile', $type );
	
	if( $type != 0 ){//上传失败
		die( $type );
	}else{
		$local_img = IMG_UPLOAD_PATH.$img;
		$img_name = end( explode('/', $local_img) );
		$del_pwd = _authCode( $img_name, 'ENCODE' );//用作删除图片的验证口令
		
		echo $img_name .'-'.$del_pwd; 
	}

}


//note 裁剪图片
function cutimg(){
	$img = _authCode( $_POST['token'], 'DECODE' );
	$pos = explode( '_', $_POST['pos'] );
	
	$im = new Image();
	
	//裁剪图片
	$up_c_img = str_replace($img, 'cut_'.$img, IMG_UPLOAD_PATH.$img );
	$ret = $im->cut( IMG_UPLOAD_PATH.$img, $up_c_img, $pos[0], $pos[1], $pos[2], $pos[3] );
	
	@unlink( IMG_UPLOAD_PATH.$img );//删除用户上传的原始图片
	echo $ret;
}

//note 删除图片
function delimg( $db ){
	$token = $_POST['token'];
	$img = _authCode( $token, 'DECODE' );
	
	@unlink( IMG_UPLOAD_PATH.$img );
	echo $img;
	
}

//note 生成图片
function createimg( $db ){
	
	$arr['from'] = $_POST['from'];
	$arr['to'] = $_POST['to'];
	$arr['by'] = $_POST['by'];
	$arr['imgstr'] = $_POST['imgstr'];
	$arr['ip'] = $_POST['ip'];
	
	$img_arr = explode(',', $arr['imgstr']);
	$img_num = count( $img_arr );
	
	$del_img = true;

	$im = new Image();
	$bg_img = IMG_UPLOAD_PATH.time().mt_rand(10,99).'.png';
	
	@copy( IMG_BG_PATH.$arr['by'].'-2.png', $bg_img );
	
	
	if( $img_num == 1 ){
		
		$img_1 = IMG_UPLOAD_PATH.'cut_' . _authCode( $img_arr[0], 'DECODE' );
		$im->zoom( $img_1, 300, 240 );//将图片缩放适应相框
		
		$r = $im->watermark( $bg_img, $img_1, 1, '', 0, '', '', 20, 110 );
		$r = $im->watermark( $r, IMG_BG_PATH.'frame-1.png', 1, '', 0, '', '', 0, 110 );
		
		if( $del_img ) @unlink( $img_1 );

	}elseif( $img_num == 2 ){

		$img_1 = IMG_UPLOAD_PATH.'cut_' . _authCode( $img_arr[0], 'DECODE' );
		$img_2 = IMG_UPLOAD_PATH.'cut_' . _authCode( $img_arr[1], 'DECODE' );

		
		$im->zoom( $img_1, 180, 150 );//将图片缩放适应相框
		$im->zoom( $img_2, 186, 162 );//将图片缩放适应相框
		
		$r = $im->watermark( $bg_img, $img_1, 1, '', 0, '', '', 10, 120 );
		$r = $im->watermark( $r, $img_2, 1, '', 0, '', '', 139, 224 );
		$r = $im->watermark( $r, IMG_BG_PATH.'frame-2.png', 1, '', 0, '', '', 0, 112 );
		
		if( $del_img ){
			@unlink( $img_1 );
			@unlink( $img_2 );
		}

	}elseif( $img_num == 3 ){
		
		$img_1 = IMG_UPLOAD_PATH.'cut_' . _authCode( $img_arr[0], 'DECODE' );
		$img_2 = IMG_UPLOAD_PATH.'cut_' . _authCode( $img_arr[1], 'DECODE' );
		$img_3 = IMG_UPLOAD_PATH.'cut_' . _authCode( $img_arr[2], 'DECODE' );
		
		//echo $img_1.'----'.$img_2.'----'.$img_3;
		
		$im->zoom( $img_1, 180, 150 );//将图片缩放适应相框
		$im->zoom( $img_2, 186, 162 );//将图片缩放适应相框
		$im->zoom( $img_3, 134, 110 );//将图片缩放适应相框
		
		$r = $im->watermark( $bg_img, $img_1, 1, '', 0, '', '', 10, 126 );
		$r = $im->watermark( $r, $img_3, 1, '', 0, '', '', 10, 290 );
		$r = $im->watermark( $r, $img_2, 1, '', 0, '', '', 139, 210 );
		$r = $im->watermark( $r, IMG_BG_PATH.'frame-3.png', 1, '', 0, '', '', 0, 118 );
		
		if( $del_img ){
			@unlink( $img_1 );
			@unlink( $img_2 );
			@unlink( $img_3 );
		}
		
	}
	
	if( $arr['by'] == 'car' ){
		$fx = 10;
		$fy = 30;
		$tx = 240;
		$ty = 26;
	}elseif( $arr['by'] == 'plane' ){
		$fx = 16;
		$fy = 56;
		$tx = 220;
		$ty = 15;
	}elseif( $arr['by'] == 'ship' ){
		$fx = 42;
		$fy = 12;
		$tx = 237;
		$ty = 40;
	}
	
	$from = _wipeChar( $arr['from'] );
	$to = _wipeChar( $arr['to'] );
	
	$r = $im->watermark( $r, '', 1, $from, 10, '#3778B4', '../../christmas/class/arial.ttf', $fx, $fy );
	$r = $im->watermark( $r, '', 1, $to, 10, '#3778B4', '../../christmas/class/arial.ttf', $tx, $ty );
	
	if( is_int( $r ) ){
		exit('error:'.$r);
	}else{
		$arr['photo'] = end( explode('/',$r));
		$arr['way'] = $arr['by'];
		$arr['day'] = strtotime( date('Y-m-d') );
		unset( $arr['by'] );
		unset( $arr['imgstr'] );
		$ret = $db->insert('photo', $arr );;
		echo 'c='.$ret.'&p='.substr($arr['photo'],0,-4);
	}

}

//note 用户填写feel,并将feel生成到图片中去
function setfeel( $db ){
	$cid = $_POST['cid'];
	$photo = $_POST['photo'];
	$feel = $_POST['feel'];
	
	$feel = substr( $feel, 0, 140 );
	
	$word = _partStr( $feel, 44 );

	$im = new Image();
	
	$r = $im->watermark( IMG_UPLOAD_PATH.$photo.'.png', '', 1, _wipeChar( $word[0] ), 10, '#3778B4', '../../christmas/class/arial.ttf', 20, 450 );
	
	foreach( $word as $k=>$v ){
		if( $k == 0 ) continue;
		$r = $im->watermark( $r, '', 1, _wipeChar( $word[$k] ), 10, '#3778B4', '../../christmas/class/arial.ttf', 20, 450 + 13*$k );
	}

	if( is_int( $r ) ){
		exit('error:'.$r);
	}
	
	rename( $r, IMG_UPLOAD_PATH.$photo.'.png');
	
	$db->update('photo', array('feel'=>$feel), 'cid='.$cid);
	
	$count = $db->getCount('photo', 'day = '.strtotime( date('Y-m-d') ));
	
	echo $count;
}

//note 用户填写用户名和邮箱
function setne( $db ){
	$cid = $_POST['cid'];
	$name = $_POST['name'];
	$email = $_POST['email'];
	$is_top20 = $_POST['is_top20'];
	
	echo $db->update('photo', array('name'=>$name,'email'=>$email, 'is_top20'=>$is_top20), 'cid='.$cid);
}


//note 根据cid取得所在关于图片信息
function getinfo( $db ){
	$cid = $_GET['cid'];
	
	$info = $db->getOne('photo', 'cid='.$cid);
	echo serialize( $info );
}


//note 取得所有展示数
function get_show_num( $db ){
	echo $num = $db->getCount('photo', 1);
}

//note 取得gallery
function get_gallery( $db ){
	$type = $_GET['type'];
	$limit = $_GET['limit'];
	
	if( $type == 'new' ){
		$sql = "SELECT cid,photo,name FROM ".DB_TABLE_PRE."photo ORDER BY cid DESC LIMIT 0, {$limit}";
	}else{
		$sql = "SELECT cid,photo,name FROM ".DB_TABLE_PRE."photo ORDER BY visit DESC LIMIT 0, {$limit}";
	}
	
	$data['item'] = $db->getAll( $sql );
	$num = $db->getCount('photo',1);
	
	$data['total'] = $num;
	
	echo serialize( $data );	
}

//note 取得gallery具体列表项
function get_gallery_item( $db ){
	$type = $_GET['type'];
	$item_id = $_GET['id'];
	
	if( $type == 'new' ){
		$sql = "SELECT cid,photo,name FROM ".DB_TABLE_PRE."photo ORDER BY cid DESC LIMIT {$item_id}, 1";
	}else{
		$sql = "SELECT cid,photo,name FROM ".DB_TABLE_PRE."photo ORDER BY visit DESC LIMIT {$item_id}, 1";
	}
	
	$data = $db->getOne( $sql );
	echo serialize( $data );
}

//note 取得top20
function get_top20( $db ){
	$sql = "SELECT cid,name FROM ".DB_TABLE_PRE."photo WHERE is_top20 = 1 ORDER BY cid DESC LIMIT 0, 20";
	$data = $db->getAll( $sql );
	echo serialize( $data );
}


//note 设置用户访问量
function setvisit( $db ){
	$cid = $_GET['cid'];
	
	$sql = "UPDATE ".DB_TABLE_PRE."photo SET visit = visit + 1 WHERE cid = {$cid}";
	echo $db->query( $sql );
}


//note 删除无用图片信息
function admin_del( $db ){
	$cid = $_GET['cid'];
	$d = $db->getOne('photo','cid='.$cid);
	
	if( !empty( $d )){
		$db->delete('photo','cid='.$cid);
		@unlink( IMG_UPLOAD_PATH.$d['photo'] );
		echo 'Success!';
	}else{
		echo 'Faile! No this photo!';
	}
}

//---------------------------------------------------------------//
$m = $_GET['m'];
$m( $db );

//创建多级目录
function _createFolder($path, $mask=0777){
   if (!is_dir( $path )){
	    _createFolder(dirname($path));
	    umask(0);
	    mkdir($path, $mask);
   }
}

//去除特殊字符
function _wipeChar( $str ){
	$str = str_replace('\\', '', $str );//去掉反斜线
	$str = preg_replace('/\s/',' ',$str);//将换行符换成空格
	return $str;
}
/**
 * 将字符串按每行多少字符，以单词分割到数组中
 * @param string $text 要分割的字符串
 * @param integer $line_char_num 每行的字符数
 * @return array
 * */
function _partStr( $text, $line_char_num ){
	$word = explode(' ', $text );
	$word_count = count( $word );
	
	$str = '';
	$word_arr = array();	
	
	for( $i = 0; $i < $word_count; $i++ ){
		$str .= $word[$i] .' ';
		
		if( strlen( $str ) > $line_char_num ){
			$word_arr[] = substr($str, 0, strrpos($str,' ') );
			$str = '';
		}
	}
	
	if( $str ) $word_arr[] = $str;

	return $word_arr;
}

/**
* 采用RC4为核心算法，通过加密或者解密用户信息
* @param $string - 加密或解密的串
* @param $operation - DECODE 解密；ENCODE 加密
* @param $key - 密钥 
* @return 返回字符串
*/
function _authCode($string, $operation = 'DECODE', $key = 'AuthCode', $expiry = 0) {

	/**
	* $ckey_length 随机密钥长度 取值 0-32;
	* 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	* 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	* 当此值为 0 时，则不产生随机密钥
	*/
	$ckey_length = 0;
	$key = md5($key);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}
